import * as apis from 'services/coupon'

const types = {
  GET_CERTIFICATE_SUCCESS: 'GET_CERTIFICATE_SUCCESS',
  CERTIFICATE_RECEIVE_SUCCESS: 'CERTIFICATE_RECEIVE_SUCCESS',
  CERTIFICATE_RECEIVE_FAILURE: 'CERTIFICATE_RECEIVE_FAILURE',
  GET_MY_INVITE_CONVERSION_CODE: 'GET_MY_INVITE_CONVERSION_CODE',
  CLOSE_POPUP_MODAL: 'CLOSE_POPUP_MODAL',
}

const state = {
  certificateStatus: '2', // 1:success 2:failure
  shareUrl: '',
  certificateData: {},
  certificateInfo: {},
  popupModal: false,
}

const actions = {
  getCertificate({ commit }, activityId) {
    return apis.getCertificate(activityId)
      .then((res) => {
        if (res.code === 1000) {
          commit(types.GET_CERTIFICATE_SUCCESS, res.data)
        }
        return res.data
      })
  },

  certificateReceive({ commit }, activityId) {
    return apis.certificateReceive(activityId)
      .then((res) => {
        if (res.code === 1000) {
          commit(types.CERTIFICATE_RECEIVE_SUCCESS, res.data)
        }
        return res
      })
  },
  getMyInviteConversionCode({ commit }) {
    apis.getMyInviteConversionCode()
      .then(res => commit(types.GET_MY_INVITE_CONVERSION_CODE, res.data))
  },
  closePopupModal({ commit }) {
    commit(types.CLOSE_POPUP_MODAL)
  },
}

const mutations = {
  [types.GET_CERTIFICATE_SUCCESS](state, data) {
    state.certificateInfo = data
  },

  [types.CERTIFICATE_RECEIVE_SUCCESS](state, data) {
    state.certificateData = data
    state.popupModal = true
    // state.certificateStatus = '1'
  },

  [types.CLOSE_POPUP_MODAL](state) {
    state.popupModal = false
  },

  // [types.CERTIFICATE_RECEIVE_FAILURE](state) {
  //   state.certificateStatus = '2'
  // },

  [types.GET_MY_INVITE_CONVERSION_CODE](state, data) {
    state.myInviteData = data
    const { currencySymbol, mainUserCouponExchangeAmount, remainUserCouponExchangeAmount, code }
      = data
    const amountStr = encodeURIComponent(currencySymbol + mainUserCouponExchangeAmount)
    const mycode = encodeURIComponent(code)
    const remainAmountStr = encodeURIComponent(currencySymbol + remainUserCouponExchangeAmount)
    state.shareUrl = `http://mapi.in.juanpi.com/offers/share/?code=${mycode}&amountStr=${amountStr}&remainAmountStr=${remainAmountStr}`
  },
}

export default {
  state,
  actions,
  mutations,
}
